package org.spring.aicloud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.spring.aicloud.entity.Answer;
import okhttp3.*;
import org.json.JSONObject;
import org.spring.aicloud.entity.enums.AIModelEnum;
import org.spring.aicloud.entity.enums.AITypeEnum;
import org.spring.aicloud.service.IAnswerService;
import org.spring.aicloud.utils.ResponseEntity;
import org.spring.aicloud.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author yexiebao
 * @date 2025/6/1
 * deepseek大模型
 */
@RestController
@RequestMapping("/deepseek")
public class DeepseekController {
    @Value("${deepseek.api-key}")
    private String apiKey;
    @Resource
    private IAnswerService answerService;

    /**
     * 对话
     * @param question
     * @return
     * @throws IOException
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) throws IOException {
        if(!StringUtils.hasLength(question)){
             return ResponseEntity.error("请先输入内容");
        }
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");

        String safeQuestion = question.replace("\"", "\\\"");

        String json = String.format("""
            {
              "messages": [
                {"role": "user", "content": "%s"}
              ],
              "model": "deepseek-chat",
              "temperature": 1,
              "top_p": 1,
              "max_tokens": 2048,
              "frequency_penalty": 0,
              "presence_penalty": 0,
              "stream": false,
              "tool_choice": "none",
              "logprobs": false
            }
            """, safeQuestion);

        RequestBody body = RequestBody.create(mediaType, json);

        Request request = new Request.Builder()
                .url("https://www.chataiapi.com/v1/chat/completions")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey) //
                .build();

        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();

        if (!response.isSuccessful()) {
            System.out.println("请求失败：" + response.code());
            System.out.println("响应内容：" + responseBody);
            throw new IOException("Unexpected code " + response);
        }

        JSONObject obj = new JSONObject(responseBody);
        String result= obj.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");
        //保存到数据库
        Answer answer = new Answer();
        answer.setTitle(question);
        answer.setContent(result.trim());
        answer.setModel(AIModelEnum.DEEPSEEK.getCode());
        answer.setType(AITypeEnum.CHAT.getCode());
        answer.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean saveResult = answerService.save(answer);
        if(!saveResult){
            return ResponseEntity.error("结果保存失败");
        }
        return ResponseEntity.ok(result.trim());
    }
     /**
     * 图片生成
     * @param question
     * @return
     * @throws IOException
     */
     @RequestMapping("/draw")
      public ResponseEntity draw(String question) throws IOException {
          if(!StringUtils.hasLength(question)){
             return ResponseEntity.error("请先输入内容");
         }
          return ResponseEntity.ok("DeepSeek图像生成接口暂未开放!");
     }
      /**
     * 获取对话列表
     * @return
     */
      @RequestMapping("/getchatlist")
      public ResponseEntity getChatList() {
          Long uid = SecurityUtil.getCurrentUser().getUid();
          QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
          queryWrapper.eq( "uid", uid);
          queryWrapper.eq("type", AITypeEnum.CHAT.getCode());
          queryWrapper.eq("model", AIModelEnum.DEEPSEEK.getCode());
          queryWrapper.orderByDesc("aid");
          return ResponseEntity.ok(answerService.list(queryWrapper));
      }/**
     * 获取图片列表
     * @return
     */
      @RequestMapping("/getdrawlist")
      public ResponseEntity getDrawList() {
           return  ResponseEntity.ok("DeepSeek图像生成接口暂未开放!");
      }

      @XxlJob("testJob")
      public void testJob(){
          System.out.println("执行了定时任务！");
      }
}
